// Modal.vue
<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    :defaultFullscreen="true"
    :footer="null"
  >
    <div style="display: flex">
      <BasicTable
        class="w-1/3 xl:w-1/3"
        @register="registerGroupTable"
        title="检查表分组管理"
        :pagination="false"
        :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
      >
        <template #toolbar>
          <a-button type="primary" @click="onAddCheckFormGroupButtonClick">新增</a-button>
        </template>
        <template #status="{ record }">
          <a-tag v-if="record.status == 0" color="green"> 正常 </a-tag>
          <a-tag v-else-if="record.status == 5" color="red">禁用</a-tag>
          <a-tag v-else>已删除</a-tag>
        </template>
        <template #action="{ column, record }">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                onClick: onEditCheckFormGroupButtonClick.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: onDeleteCheckFormGroupButtonClick.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
      <BasicTable
        class="w-2/3 xl:w-2/3"
        :data-source="ItemTableData"
        :search-info="selectedRowKeys[0]"
        @register="registerItemTable"
        title="检查表分组项目管理"
        :pagination="false"
        :scroll="{ x: false, y: 'calc(100vh - 230px)' }"
      >
        <template #toolbar>
          <a-button type="primary" @click="onAddCheckFormItemButtonClick">新增</a-button>
        </template>
        <template #status="{ record }">
          <a-tag v-if="record.status == 0" color="green"> 正常 </a-tag>
          <a-tag v-else-if="record.status == 5" color="red">禁用</a-tag>
          <a-tag v-else>已删除</a-tag>
        </template>
        <template #options="{ record }">
          {{
            JSON.parse(record.options)
              .map((item) => item.label)
              .join(',')
          }}
        </template>
        <template #action="{ column, record }">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                onClick: onEditCheckFormItemButtonClick.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: onDeleteCheckFormItemButtonClick.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>

    <AddOrUpdateCheckGroupForm @register="registerAddOrUpdateCheckGroupForm" @success="opSuccess" />
    <AddOrUpdateCheckItem @register="registerAddOrUpdateCheckItemForm" @success="opSuccess" />
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, nextTick, unref, watch } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    getOneCheckFormGroup,
    deleteCheckGroup,
    getCheckGroupItem,
    deleteCheckItem,
  } from '/@/api/ehs/checkForm';
  import { checkFormGroupColumns, checkFormItemColumns } from './checkForm.data';
  const { createMessage } = useMessage();
  import AddOrUpdateCheckGroupForm from './AddOrUpdateCheckGroupForm.vue';
  import AddOrUpdateCheckItem from './AddOrUpdateCheckItem.vue';
  export default defineComponent({
    components: {
      BasicModal,
      BasicTable,
      TableAction,
      AddOrUpdateCheckGroupForm,
      AddOrUpdateCheckItem,
    },
    name: 'ViewCheckFormGroupModal',
    setup() {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const tableid = ref();
      const selectedRowKeys = ref([]);
      const ItemTableData = ref([]);
      const [registerAddOrUpdateCheckGroupForm, { openModal: openAddOrUpdateCheckFormGroupModal }] =
        useModal();
      const [registerAddOrUpdateCheckItemForm, { openModal: openAddOrUpdateCheckFormItemModal }] =
        useModal();
      const [registerGroupTable, { reload: reloadGroupTable }] = useTable({
        api: getOneCheckFormGroup,
        columns: checkFormGroupColumns,
        canResize: true,
        striped: true,
        showTableSetting: true,
        immediate: false,
        bordered: true,
        showIndexColumn: false,
        ellipsis: true,
        beforeFetch: (params) => {
          params = tableid.value;
          return params;
        },
        afterFetch: (data) => {
          if (data == null) {
            return [];
          }
        },
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        rowKey: 'groupid',
        rowSelection: computed(() => {
          return {
            selectedRowKeys: unref(selectedRowKeys),
            type: 'radio',
            onChange: (key) => {
              // console.log(key, 'key');
              if (key.length < 1) return;
              ItemTableData.value = [];
              if (key.length > 0) {
                selectedRowKeys.value = key;
                getItemTableData(key[0]);
              }
            },
          };
        }),
      });

      const [registerItemTable, { setTableData: setItemTableData }] = useTable({
        columns: checkFormItemColumns,
        canResize: true,
        striped: true,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: false,
        ellipsis: true,
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      const [register, { closeModal }] = useModalInner((data) => {
        ItemTableData.value = [];
        selectedRowKeys.value = [];
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.tableid) {
            tableid.value = unrefData.tableid;
            reloadGroupTable();
          }
        }
      });

      function getItemTableData(groupid) {
        if (groupid) {
          getCheckGroupItem(groupid).then((res) => {
            ItemTableData.value = res ?? [];
          });
        } else {
          ItemTableData.value = [];
        }
      }

      // 新增分组
      function onAddCheckFormGroupButtonClick(record) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '分组管理',
          operateType: OperationTypeEnum.ADD,
          tableid: tableid.value,
        };
        openAddOrUpdateCheckFormGroupModal(true, propsData);
      }
      // 编辑分组
      function onEditCheckFormGroupButtonClick(record) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '分组管理',
          operateType: OperationTypeEnum.EDIT,
          tableid: tableid.value,
          groupid: record.groupid,
        };
        openAddOrUpdateCheckFormGroupModal(true, propsData);
      }
      //删除分组
      function onDeleteCheckFormGroupButtonClick(record) {
        deleteCheckGroup(record.groupid)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              opSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      // 新增项目
      function onAddCheckFormItemButtonClick(record) {
        if (selectedRowKeys.value.length < 1) return createMessage.error('请选择分组。', 2);
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '分组项目管理',
          operateType: OperationTypeEnum.ADD,
          tableid: tableid.value,
          groupid: selectedRowKeys.value[0],
        };
        openAddOrUpdateCheckFormItemModal(true, propsData);
      }
      // 编辑项目
      function onEditCheckFormItemButtonClick(record) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '分组项目管理',
          operateType: OperationTypeEnum.EDIT,
          tableid: tableid.value,
          groupid: selectedRowKeys.value[0],
          itemid: record.itemid,
        };
        openAddOrUpdateCheckFormItemModal(true, propsData);
      }
      //删除项目
      function onDeleteCheckFormItemButtonClick(record) {
        deleteCheckItem(record.itemid)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              opSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      function opSuccess() {
        reloadGroupTable();
        if (selectedRowKeys.value.length > 0) getItemTableData(selectedRowKeys.value[0]);
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      return {
        selectedRowKeys,
        ItemTableData,
        register,
        registerGroupTable,
        registerItemTable,
        registerAddOrUpdateCheckGroupForm,
        registerAddOrUpdateCheckItemForm,
        closeModal,
        opSuccess,
        displayModuleTitle,
        onAddCheckFormGroupButtonClick,
        onEditCheckFormGroupButtonClick,
        onDeleteCheckFormGroupButtonClick,
        onAddCheckFormItemButtonClick,
        onEditCheckFormItemButtonClick,
        onDeleteCheckFormItemButtonClick,
      };
    },
  });
</script>
